package com.xinlong.shop.framework.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.xinlong.shop.framework.cache.ICache;
import com.xinlong.shop.framework.cache.model.CacheModel;
import com.xinlong.shop.framework.service.ICaptchaService;
import org.springframework.stereotype.Service;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 22:44 2023/1/1
 */
@Service
public class CaptchaServiceImpl implements ICaptchaService {

    private final ICache<CacheModel> cache;

    private static final String CAPTCHA_PREFIX = "CAPTCHA_";

    public CaptchaServiceImpl(ICache cache) {
        this.cache = cache;
    }


    @Override
    public String createCaptcha(String keyId) {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        // 验证码值
        String code = lineCaptcha.getCode();
        // 获取5分钟后的时间戳（验证码有效期5分钟）
        Long expirationTime = DateUtil.offset(DateUtil.date(), DateField.MINUTE, 5).getTime();
        CacheModel cacheModel = new CacheModel(code, expirationTime);
        this.cache.put(CAPTCHA_PREFIX + keyId, cacheModel);

        return lineCaptcha.getImageBase64Data();
    }

    @Override
    public boolean verify(String code, String keyId) {
        CacheModel cacheModel = this.cache.get(CAPTCHA_PREFIX + keyId);

        if (cacheModel == null) {
            return false;
        }

        if (cacheModel.getValue().equals(code)) {

            // 判断是否过期 当前时间大于过期时间
            if (DateUtil.date().getTime() > cacheModel.getExpirationTime()) {
                return false;
            }
            // 成功后删除
            this.cache.delete(keyId);
            return true;
        }
        return false;
    }

}
